package com.dataextend.service;

import com.alibaba.fastjson.JSONObject;
import com.dataextend.common.utils.CommonUtil;
import com.dataextend.dto.GroupAnalysisListDTO;
import com.dataextend.dto.PropertyAndActDTO;
import com.dataextend.dto.PropertyListInfoDTO;
import com.dataextend.entity.ResponseUserTag;
import com.dataextend.entity.UserProfileTag;
import com.dataextend.mapper.cluster.UserGroupMapper;
import com.dataextend.mapper.cluster.UserProfileMapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


/**
 *   用户画像—— 用户标签模块
 */
@Slf4j
@Service
public class UserProfileService {
    @Autowired
    private UserProfileMapper userProfileMapper;
    @Autowired
    private UserGroupMapper userGroupMapper;



    /**
     *  首页查询用户标签视图,展开是树形结构
     */
    public JSONObject userTagView(){
        List<JSONObject> userTagView = userProfileMapper.userTagView();
        JSONObject map = new JSONObject(true);
        // 添加树形结构的头部信息
//        map.put("用户标签", userTagView);
        String label = "{\"position\":\"right\"}";
        map.put("name", "用户标签");
//        map.put("label", JSONObject.parse(label));
        map.put("children", userTagView);
        return map;
    }


    /**
     *  根据标签ID进行查询
     */
    public JSONObject searchTagId(String tagId){
        log.info("--->查询的标签名称: " + tagId);
        List<JSONObject> usertaglist = userProfileMapper.searchTagId(tagId);
        List<ResponseUserTag> returnList = new ArrayList<>();
        JSONObject returnResult = new JSONObject(true);
        for (JSONObject usertag :usertaglist){
            ResponseUserTag userTagInfo = new ResponseUserTag();
            String tag_id = usertag.getString("tag_id");
            userTagInfo.setTag_id(tag_id);
            String tag_name = usertag.getString("tag_name");
            userTagInfo.setTag_name(tag_name);
            String level_1_name = usertag.getString("level_1_name");
            userTagInfo.setLevel_1_name(level_1_name);
            String level_2_name = usertag.getString("level_2_name");
            userTagInfo.setLevel_2_name(level_2_name);
            String user_type = usertag.getString("user_type");
            userTagInfo.setUser_type(user_type);
            String tag_type = usertag.getString("tag_type");
            if (tag_type.equals("1")){
                userTagInfo.setTag_type("分类");
            } else {
                userTagInfo.setTag_type("统计");
            }
            String develop_type = usertag.getString("develop_type");
            if (develop_type.equals("1")){
                userTagInfo.setDevelop_type("算法");
            } else {
                userTagInfo.setDevelop_type("非算法");
            }
            String exclusion = usertag.getString("exclusion");
            if (exclusion.equals("1")){
                userTagInfo.setExclusion("互斥");
            } else {
                userTagInfo.setExclusion("非互斥");
            }
            String is_online = usertag.getString("is_online");
            if (is_online.equals("1")){
                userTagInfo.setIs_online("使用中");
            } else {
                userTagInfo.setIs_online("已停用");
            }
            String tag_desc = usertag.getString("tagdesc");
            userTagInfo.setTag_desc(tag_desc);
            returnList.add(userTagInfo);
        }
        returnResult.put("list", returnList);
        returnResult.put("total", returnList.size());
        return returnResult;
    }


    /**
     *  标签数量校验
     */
    public JSONObject checkTagNum(String tagId, String startDate, String endDate){
        List<JSONObject> tagNumList = userProfileMapper.checkTagNum(tagId, startDate, endDate);
        JSONObject map = new JSONObject();
        map.put("list", tagNumList);
        return map;
    }


    /**
     *  同二级大类下各标签所占比例
     */
    public JSONObject checkTagRatio(String tagId, String dataDate){
        JSONObject map = new JSONObject();
        List<JSONObject> tagNumList = userProfileMapper.checkTagRatio(tagId.substring(0,7), dataDate);
        map.put("list", tagNumList);
        return map;
    }



    /**
     *  新增用户标签
     */
    public JSONObject addUserTag(UserProfileTag userProfileTag){
        userProfileMapper.addUserTag(userProfileTag);
        return CommonUtil.successJson();
    }


    /**
     *  删除用户标签
     */
    public JSONObject deleteUserTag(String tag_id){
        userProfileMapper.deleteUserTag(tag_id);
        return CommonUtil.successJson();
    }


    /**
     *  修改用户标签
     */
    public JSONObject updateUserTag(UserProfileTag userProfileTag){
        userProfileMapper.updateUserTag(userProfileTag);
        return CommonUtil.successJson();
    }


    /**
     *  根据标签名称进行查询
     */
    public JSONObject searchUserTag(String tagname){
        List<JSONObject> usertaglist = userProfileMapper.searchUserTag(tagname);
        List<ResponseUserTag> returnList = new ArrayList<>();
        JSONObject returnResult = new JSONObject(true);
        for (JSONObject usertag :usertaglist){
            ResponseUserTag userTagInfo = new ResponseUserTag();
            String tag_id = usertag.getString("tag_id");
            userTagInfo.setTag_id(tag_id);
            String tag_name = usertag.getString("tag_name");
            userTagInfo.setTag_name(tag_name);
            String level_1_name = usertag.getString("level_1_name");
            userTagInfo.setLevel_1_name(level_1_name);
            String level_2_name = usertag.getString("level_2_name");
            userTagInfo.setLevel_2_name(level_2_name);
            String user_type = usertag.getString("user_type");
            userTagInfo.setUser_type(user_type);
            String tag_type = usertag.getString("tag_type");
            if (tag_type.equals("1")){
                userTagInfo.setTag_type("分类");
            } else {
                userTagInfo.setTag_type("统计");
            }
            String develop_type = usertag.getString("develop_type");
            if (develop_type.equals("1")){
                userTagInfo.setDevelop_type("算法");
            } else {
                userTagInfo.setDevelop_type("非算法");
            }
            String exclusion = usertag.getString("exclusion");
            if (exclusion.equals("1")){
                userTagInfo.setExclusion("互斥");
            } else {
                userTagInfo.setExclusion("非互斥");
            }
            String is_online = usertag.getString("is_online");
            if (is_online.equals("1")){
                userTagInfo.setIs_online("使用中");
            } else {
                userTagInfo.setIs_online("已停用");
            }
            String tag_desc = usertag.getString("tag_desc");
            userTagInfo.setTag_desc(tag_desc);
            returnList.add(userTagInfo);
        }
        returnResult.put("list", returnList);
        returnResult.put("total", returnList.size());
        return returnResult;
    }



    /**
     *  用户标签列表 分页展示
     */
    public JSONObject listUserTag(Integer pageNo, Integer pageSize){
        int count = userProfileMapper.countUserTag();
        Integer paramPageno = (pageNo - 1) * pageSize;
        Integer paramPagesize = pageSize;
        List<JSONObject> list = userProfileMapper.listUserTag(paramPageno, paramPagesize);
        List<ResponseUserTag> returnList = new ArrayList<>();
        for (JSONObject usertag :list){
            ResponseUserTag userTagInfo = new ResponseUserTag();
            String tag_id = usertag.getString("tag_id");
            userTagInfo.setTag_id(tag_id);
            String tag_name = usertag.getString("tag_name");
            userTagInfo.setTag_name(tag_name);
            String level_1_name = usertag.getString("level_1_name");
            userTagInfo.setLevel_1_name(level_1_name);
            String level_2_name = usertag.getString("level_2_name");
            userTagInfo.setLevel_2_name(level_2_name);
            String user_type = usertag.getString("user_type");
            userTagInfo.setUser_type(user_type);
            String tag_type = usertag.getString("tag_type");
            if (tag_type.equals("1")){
                userTagInfo.setTag_type("分类");
            } else {
                userTagInfo.setTag_type("统计");
            }
            String develop_type = usertag.getString("develop_type");
            if (develop_type.equals("1")){
                userTagInfo.setDevelop_type("算法");
            } else {
                userTagInfo.setDevelop_type("非算法");
            }
            String exclusion = usertag.getString("exclusion");
            if (exclusion.equals("1")){
                userTagInfo.setExclusion("互斥");
            } else {
                userTagInfo.setExclusion("非互斥");
            }
            String is_online = usertag.getString("is_online");
            if (is_online.equals("1")){
                userTagInfo.setIs_online("使用中");
            } else {
                userTagInfo.setIs_online("已停用");
            }
            String tag_desc = usertag.getString("tag_desc");
            userTagInfo.setTag_desc(tag_desc);
            returnList.add(userTagInfo);
        }


        return CommonUtil.successPageTag(pageNo, pageSize, returnList, count);
    }


    /**
     *  用户画像 —— 人群多维分析— 下拉菜单 筛选分析维度
     */
    public JSONObject usergroupAnalysisList(){
        List<JSONObject> dimension = userProfileMapper.usergroupAnalysisList();
        log.info("--->人群多维分析— 下拉菜单 筛选分析维度: {}" , dimension);
        return CommonUtil.successPage(dimension);
    }


    /**
     *  用户画像 —— 人群多维分析 —— 填写标签权重值
     */
    public JSONObject usergroupAnalysisTags(String level_2_name, String tag_type){
        List<JSONObject> tags = new ArrayList<>();
        if (tag_type.equals("1")){
            tags = userProfileMapper.usergroupAnalysisTheme(level_2_name);
        } else {
            tags = userProfileMapper.usergroupAnalysisTag(level_2_name);
        }
        return CommonUtil.successPage(tags);
    }


    /**
     *  用户画像 —— 人群多维分析-选择人群
     */
    public List<JSONObject> distinctGroupname(){
        List<JSONObject> groupNames = userProfileMapper.distinctGroupname();
        return groupNames;
    }


    /**
     *  用户画像 —— 人群多维分析-根据人群id查询人群规则
     */
    public JSONObject usergroupRule(String groupId){
        String groupRule = userProfileMapper.usergroupRule(groupId);
        return JSONObject.parseObject(groupRule);
    }


    /**
     *  用户画像 —— 人群多维分析-根据分析维度查询包含的标签
     */
    public List<String> analysisTags(String dimension){
        List<String> groupRule = userProfileMapper.analysisTags(dimension);
        return groupRule;
    }


    /** 用户属性满足条件筛选  */
    public List<JSONObject> propertyFilterList() {
        return userProfileMapper.propertyFilterList();
    }


    /** 人群分析下拉菜单  */
    public List<JSONObject> analysisList() {
        return userProfileMapper.analysisList();
    }


    /** 人群分析维度列表  */
    public List<String> analysisDimensionList() {
        return userProfileMapper.analysisDimensionList();
    }


    /**  人群分析维度新增删除 */
    public void analysisDimensionEditAndadd(String dimension, String type) {
        if (type.equals("add")) {
            userProfileMapper.analysisDimensionAdd(dimension);
        } else {
            userProfileMapper.analysisDimensionDelete(dimension);
        }
    }


    /**  用户画像 —— 圈人计算获取groupId  */
    public String propertyAndActGetgroupId() {
        String maxGroupId = userProfileMapper.maxGroupId();
        Integer id = Integer.valueOf(maxGroupId.replace("user_group_", ""));
        return "user_group_" + String.format("%0" + 4+ "d", id+1);
    }


    /**  人群分析列表页  */
    public JSONObject list(GroupAnalysisListDTO groupAnalysisListDTO) {
        Integer pageno = (groupAnalysisListDTO.getPageNo() - 1) * groupAnalysisListDTO.getPageSize();
        List<JSONObject> groupResult = new ArrayList<>();
        List<JSONObject> groupList = userGroupMapper.getUserGroupList(groupAnalysisListDTO.getGroupInfo(), pageno, groupAnalysisListDTO.getPageSize());
        for (JSONObject group :groupList) {
            JSONObject detail = new JSONObject(true);
            detail.put("groupId", group.getString("group_id"));
            detail.put("groupName", group.getString("group_name"));
            detail.put("creator", group.getString("creator"));
            detail.put("createTime", group.getString("create_time"));
            detail.put("num", group.getInteger("num"));
            detail.put("comment", group.getString("comment"));
            detail.put("rule_type", group.getString("rule_type"));
            //把JSON字符串转为对象
            Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            PropertyAndActDTO.propertyRules propertyRules = gson.fromJson(group.getString("property_rules"), new TypeToken<PropertyAndActDTO.propertyRules>(){}.getType());
            detail.put("propertyRules", propertyRules);
            PropertyAndActDTO.actRules actRules = gson.fromJson(group.getString("act_rules"), new TypeToken<PropertyAndActDTO.actRules>(){}.getType());
            detail.put("actRules", actRules);
            groupResult.add(detail);
        }

        Integer groupNum = userGroupMapper.getUserGroupNum(groupAnalysisListDTO.getGroupInfo());
        JSONObject result = new JSONObject(true);
        result.put("list", groupResult);
        result.put("num", groupNum);
        return result;
    }



    /**  人群删除  */
    public void delete(String groupId) {
        userGroupMapper.groupDelete(groupId);
    }



    /**  用户属性筛选菜单  */
    public List<PropertyListInfoDTO> propertyList() {
        return userGroupMapper.propertyList();
    }


}
